# !/usr/bin/env python3
# -*- coding: utf-8 -*-

from numpy import *
import operator

from pip._vendor.distlib.compat import raw_input


# 创建数据集
def createDataSet():
    group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
    labels = ['A', 'A', 'B', 'B']
    return group, labels


# 2-1
# kNNAlgo algorithm
# inX       :   待分类向量
# dataSet   :   训练样本集
# labels    :   已知标签向量
# k         :   选择的最近邻近数目
def classify0(inX, dataSet, labels, k):
    # 距离计算
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX, (dataSetSize, 1)) - dataSet
    sqDiffMat = diffMat ** 2
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances ** 0.5
    sortedDistIndicies = distances.argsort()
    classCount = {}
    # 选择最小K个点
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
    # 排序
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]


# #copy 创建已分类数据标签集
# import numpy as np
# import operator
# def createDataSet():
#     group = array([1.0, 1.1],
#                   [1.0, 1.0],
#                   [0, 0],
#                   [0, 0.1])
#     labels = ['A', 'A', 'B', 'B']
# #kNN算法
# def classify0(inX, dataSet, labels, k):
#     dataSetSize = dataSet.shape[0] #计算数据集个数
#     diffMat = tile(inX, (dataSetSize, 1)) - dataSet #求出点差
#     sqDiffMat = diffMat ** 2 #求出点差平方
#     sqDistances = sqDiffMat.sum(axis=1) #求出点差平方和
#     distances = sqDistances ** 0.5 #点差平方和 开根号 求出四个距离
#     #排序距离
#     sortedDistIndices = distances.argsort() #求出距离从小到大的值的排序，并标记为索引号
#     classCount = {}
#     for i in range(k):
#         selectLabel = labels[sortedDistIndices[i]] #取出k个最小距离的对应的标签
#         classCount[selectLabel] = classCount.get(selectLabel, 0) + 1
#     sortedClasscount = sorted(classCount.items(), key = operator.itemgetter(1), reverse=True)
#     return sortedClasscount[0][0]

# 2-2
# 将文本记录转换为Numpy的解析程序
def file2matrix(filename):
    fr = open(filename)
    arrayOLines = fr.readlines()
    numberOfLines = len(arrayOLines)
    returnMat = zeros((numberOfLines, 3))
    classLabelVector = []
    index = 0
    for line in arrayOLines:
        line = line.strip()
        listFromLine = line.split('\t')
        returnMat[index, :] = listFromLine[0:3]
        classLabelVector.append(listFromLine[-1])
        index += 1
    return returnMat, classLabelVector


# 2-3
# 归一化特征值
def autoNorm(dataSet):
    minVals = dataSet.min(0)
    maxVals = dataSet.max(0)
    print(maxVals)
    ranges = maxVals - minVals
    normDataSet = zeros(shape(dataSet))
    m = dataSet.shape[0]
    normDataSet = (dataSet - tile(minVals, (m, 1))) / (tile(ranges, (m, 1)))
    return normDataSet, ranges, minVals


# 2-4
# 分类器针对约会网站的测试代码
def datingClassTest():
    hoRatio = 0.10
    datingDatamat, datingLabels = file2matrix('datingTestSet.txt')
    normMat, ranges, minVals = autoNorm(datingDatamat)
    m = normMat.shape[0]
    numTestVecs = int(m * hoRatio)
    errorCount = 0.0
    for i in range(numTestVecs):

        test1 = normMat[numTestVecs:m, :]
        test2 = datingLabels[numTestVecs:m]

        classifierResult = classify0(normMat[i, :], normMat[numTestVecs:m, :], datingLabels[numTestVecs:m], 3)
        print('the classifier came bac with: %s, the real answer is: %s' % (classifierResult, datingLabels[i]))
        if (classifierResult != datingLabels[i]):
            errorCount += 1.0
    print('the total error rate is : %f' % (errorCount / float(numTestVecs)))


# 2-5
# 约会网站预测函数

def classifyPerson():
    resultList = ['not at all不喜欢', 'in small doses魅力一般', 'in large doses极具魅力']
    percentTats = float(raw_input('percentage of time spent playing video games?'))
    ffMiles = float(raw_input('frequent filer miles earned per year?'))
    iceCream = float(raw_input('liters of ice cream consumed per year?'))
    datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
    normMat, ranges, minVals = autoNorm(datingDataMat)
    inArr = array([ffMiles, percentTats, iceCream])
    classifierResult = classify0((inArr - minVals) / ranges, normMat, datingLabels, 3)
    print('You will probbly ,like this person:', resultList[int(classifierResult) - 1])
